package com.it.service.impl;

import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.it.bean.Notice;
import com.it.config.WebSocket;
import com.it.dto.NoticeDTO;
import com.it.enums.NoticeType;
import com.it.mapper.NoticeMapper;
import com.it.page.PageQuery;
import com.it.service.NoticeService;
import com.it.utils.AppUtils;
import com.it.vo.NoticeVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author TBH
 * @date 2025-05-16 09:31:55
 * @desc
 */
@Service("noticeService")
@RequiredArgsConstructor
public class NoticeServiceImpl implements NoticeService {

    private final WebSocket webSocket;
    private final NoticeMapper noticeMapper;

    @Override
    public PageInfo<NoticeVo> page(PageQuery<NoticeDTO> pageQuery) {
        PageHelper.startPage(pageQuery.getPage(), pageQuery.getPageSize());
        List<NoticeVo> notices = noticeMapper.selectJoin(pageQuery.getQueryBody());
        return new PageInfo<>(notices);
    }

    @Override
    public void save(Notice notice) {
        if (notice.getId() == null) {
            notice.setStatus(NoticeType.NO_READ.getType());
            AppUtils.forSaveAudit(notice);
            noticeMapper.save(notice);
            webSocket.sendOneMessage(String.valueOf(notice.getUserId()), JSONUtil.toJsonStr(notice));
        } else {
            AppUtils.forUpdateAudit(notice);
            noticeMapper.updateByPrimaryKeySelective(notice);
        }
    }

    @Override
    public void read(Long id) {
        Notice notice = noticeMapper.selectByPrimaryKey(id);
        notice.setStatus(NoticeType.READ.getType());
        noticeMapper.updateByPrimaryKeySelective(notice);
    }
}
